package com.jixiang.goods.service.impl;

import cn.hutool.json.JSONUtil;
import com.jixiang.goods.service.GoodsEsService;
import com.jixiang.goods.service.GsGoodsInfoService;
import com.jixiang.goods.service.GsGoodsTypeService;
import com.jixiang.model.goods.entity.GsGoodsInfo;
import com.jixiang.model.goods.entity.GsGoodsType;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

import static com.jixiang.common.constants.GoodsIndexConstants.MAPPING_NAME;
@Component
public class GoodsEsServiceImpl implements GoodsEsService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private GsGoodsInfoService gsGoodsInfoService;
    @Resource
    private GsGoodsTypeService gsGoodsTypeService;

    @Override
    public void saveEsGoodsById(Long goodsId) {
        try {
            GsGoodsInfo gsGoodsInfo = gsGoodsInfoService.getById(goodsId.toString());
            GsGoodsType gsGoodsType = gsGoodsTypeService.query().eq("id", gsGoodsInfo.getGoodsTypeId()).list().get(0);
//            GsGoodsType gsGoodsType1 = gsGoodsTypeService.query().eq("id", gsGoodsType.getParentGoodsTypeId()).list().get(0);
            gsGoodsInfo.setParentGoodsTypeId(gsGoodsType.getParentGoodsTypeId());
            String jsonStr = JSONUtil.toJsonStr(gsGoodsInfo);
            IndexRequest request = new IndexRequest(MAPPING_NAME).id(goodsId.toString());
            // 2.准备请求参数DSL，其实就是文档的JSON字符串
            request.source(jsonStr, XContentType.JSON);
            // 3.发送请求
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
